/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.branchstores;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.District;
import com.qinyeit.serviceapp.entity.SyncStockRecord;
import com.qinyeit.serviceapp.entity.enums.SyncStockState;
import com.qinyeit.serviceapp.service.branchstores.SyncStockRecordService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.SyncStock;
import com.qinyeit.serviceapp.service.branchstores.SyncStockService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: SyncStocksController <br/>
 * Function: syncStock [库存数据下发] <br/>
 * date: 2018-12-12 15:38:46 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/branchstores/syncStocks")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_syncStock:read",name ="库存数据下发",deleteAble = false)
public class SyncStocksController extends BaseManagementController{

	@Autowired
	private SyncStockService syncStockService;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private SyncStockRecordService syncStockRecordService;
	private final String [] keys = {"id","branchId","name","lastTime","thisTime","state"};

    @RequiresPermissions("management_syncStock:show")
    @PermissionInfo(code = "management_syncStock:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        if (!CurrentAccountUtils.getAuthenticatedIsAdmin()){
            String permissions = CurrentAccountUtils.getAuthenticatedManageBranch();
            if (StringUtils.isNotBlank(permissions)){
                searchable.addSearchParam("branchId_in", JSON.parseArray(permissions,Long.class));
            }else {
                searchable.addSearchParam("branchId_eq",0);
            }
        }
        Page<SyncStock> syncStockPage = syncStockService.findAll(searchable);
        return ok("查询成功", JSONUtils.include(syncStockPage, new Class[]{SyncStockState.class}, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("syncStock",JSONUtils.include(new SyncStock(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_syncStock:create")
    @PermissionInfo(code = "management_syncStock:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
//        if(syncStockService.exists(buildExists(null, "no", syncStock.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        syncStockService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute SyncStock syncStock){
        return ok("查询成功", JSONUtils.include(syncStock, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute SyncStock syncStock){
        QyMap map=QyMap.NEW();
        map.setv("syncStock",JSONUtils.include(syncStock, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_syncStock:update")
    @PermissionInfo(code = "management_syncStock:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject data,BindingResult bindingResult){
//        if(syncStockService.exists(buildExists(null, "no", syncStock.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        syncStockService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_syncStock:destory")
    @PermissionInfo(code = "management_syncStock:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        syncStockService.logicDelete(id);
        return ok("删除成功", null);
    }

    @RequiresPermissions("management_syncStock:destory")
    @PermissionInfo(code = "management_syncStock:destory",name ="删除",deleteAble = false)
    @GetMapping("/showRecord")
    public Object showRecord(Long id){

        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("syncId_eq",id);
        List<SyncStockRecord> records = syncStockRecordService.findWithSort(searchable);
        return ok("查询成功", JSONUtils.include(records,new Class[]{SyncStockState.class},"thisTime","state"));
    }


    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            SyncStock syncStock = syncStockService.findById(Long.valueOf(id));
            model.addAttribute(syncStock);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //区域门店
//        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
        qyMap.setv("districts",getDistricts());
    }

}